import createjs from "createjs-ts"
import cjs=createjs
interface Force { d:number, rad:number }
export default class Bubble extends cjs.Container {
    /** 挤压方式:0每次计算移动1像素，1每次计算移动距离为“力×弹性系数” */
    static pushType:number=1
    /** 弹性系数 */
    static elasticStrength:number=0.1
    /** 圆半径 */
    private _radius=50
    /** 圆形 */
    private shape=new cjs.Shape()
    /** 绘制受力 */
    private forceshape=new cjs.Shape()
    /** 受力集合 */
    private forces:Force[]=[]
    constructor(r=50) {
        super()
        this._radius=r
        this.drawShape()
        this.addChild(this.shape)
        this.addChild(this.forceshape)
    }
    /**
     * 添加受力
     * @param d 距离（力大小）
     * @param rad 角度(弧度)
     */
    addForce(d:number,rad:number):void {
        this.forces.push({d,rad})
        
        this.turnRed()
    }
    /** 获取半径 */
    get radius():number {
        return this._radius
    }
    private drawShape(color='back'):void {
        const shape=this.shape
        shape.graphics.clear()
        shape.graphics.setStrokeStyle(1).beginStroke(color).drawCircle(0, 0, this.radius)
        shape.graphics.endStroke()
    }
    private drawLine(d:number,rad:number):void {
        const px=d*Math.cos(rad)
        const py=d*Math.sin(rad)
        this.forceshape.graphics.setStrokeStyle(1).beginStroke('#00ff00').moveTo(0, 0).lineTo(px, py)
        this.forceshape.graphics.endStroke()
    }
    /** 更新受力 */
    updateJoinForces():void {
        let x=0,y=0
        for(const f of this.forces) {
            x+=f.d*Math.cos(f.rad)
            y+=f.d*Math.sin(f.rad)
        }
        if(Bubble.pushType==0) {
            this.x+=(x>1?1:x)
            this.y+=(y>1?1:y)
        }else{
            this.x+=Bubble.elasticStrength*x
            this.y+=Bubble.elasticStrength*y
        }
    }
    /** 清除受力 */
    clear():void {
        this.forceshape.graphics.clear()
        if(this.forces.length>0){
            this.turnRed()
            for(const f of this.forces) {
                this.drawLine(f.d, f.rad)
            }
        }else{
            this.drawShape()
            
        }
        this.forces.length=0
        //
    }
    private turnRed():void {
        //this.shape.graphics.clear()
        this.drawShape('#ff0000')
    }
}